import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { getCartList, changeCount, delSelect } from "@/apis/cart"

export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    
    const removeCartInfo = () => {
      localStorage.removeItem('cart')
    }
    // 获取购物车列表
    const gainCartList = async() => {
      const { data } = await getCartList()
      data.list.forEach(item => {
        item.isChecked = true
      })
      cartList.value = data.list
    }

    // 更新购物车商品数量
    const updateCartList = async(obj) => {
      const { goodsNum, goodsId, goodsSkuId } = obj
      const goods = cartList.value.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
      await changeCount(goodsId, goodsNum, goodsSkuId)
    } 

    // 删除购物车商品数量
    const deleteCartList = async() => {
      const cartIds = selCartList.value.map(item => item.id)
      await delSelect(cartIds)
      // eslint-disable-next-line no-undef
      showToast('删除成功');
      await gainCartList()
    }
    // 让对应的id项取反
    const toggleCheck = (goodsId) => {
       const goods = cartList.value.find(item => item.goods_id === goodsId)
       goods.isChecked = !goods.isChecked
    }
    // 让所有的小选框同步设置
    const toggleAllCheck = (flag) => {
      cartList.value.forEach(item => {
        item.isChecked = flag
      })
    }
    // 所有商品的累加总数
    const cartTotal = computed(() => cartList.value.reduce((sum, item) => sum + item.goods_num, 0))
    // 选中的商品项
    const selCartList = computed(() => cartList.value.filter(item => item.isChecked))
    // 选中的商品项的总数
    const selCount = computed(() => selCartList.value.reduce((sum ,item) => sum + item.goods_num, 0))
    // 选中的总价
    const selPrice = computed(() => selCartList.value.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2))
    // 是否全选
    const isAllChecked = computed(() => cartList.value.every(item => item.isChecked))
    return {
      cartList,
      cartTotal,
      selCartList,
      selCount,
      selPrice,
      isAllChecked,
      toggleCheck,
      toggleAllCheck,
      gainCartList,
      updateCartList,
      deleteCartList,
      removeCartInfo
    }
},
{
  persist:true
}
)